import { useState, useCallback } from 'react';
import { aiApi, GenerateResponseRequest, TTSRequest, ASRRequest, HealthCheckResponse } from '@/lib/api/ai';

// AI Generation Hook
export function useAIGenerate() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const generateResponse = useCallback(async (data: GenerateResponseRequest) => {
    try {
      setLoading(true);
      setError(null);
      return await aiApi.generateResponse(data);
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || 'AI generation failed';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    generateResponse,
    loading,
    error,
  };
}

// TTS Hook
export function useTTS() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const textToSpeech = useCallback(async (data: TTSRequest) => {
    try {
      setLoading(true);
      setError(null);
      return await aiApi.textToSpeech(data);
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || 'Speech synthesis failed';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    textToSpeech,
    loading,
    error,
  };
}

// ASR Hook
export function useASR() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const speechToText = useCallback(async (data: ASRRequest) => {
    try {
      setLoading(true);
      setError(null);
      return await aiApi.speechToText(data);
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || 'Speech recognition failed';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    speechToText,
    loading,
    error,
  };
}

// AI Health Check Hook
export function useAIHealth() {
  const [health, setHealth] = useState<HealthCheckResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const checkHealth = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const result = await aiApi.checkHealth();
      setHealth(result);
      return result;
    } catch (err: any) {
      const errorMessage = err.response?.data?.message || 'Health check failed';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    health,
    checkHealth,
    loading,
    error,
  };
}
